package com.khyr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.khyr.Vo.DrugSalesListVo;
import com.khyr.Vo.NameAndDateVo;
import com.khyr.Vo.RevenueAndExpenditureStatisticsVo;
import com.khyr.Vo.StatisticalListOfDrugSalesVo;
import com.khyr.dao.ChargeDao;
import com.khyr.dao.DrugStatisticsDao;
import com.khyr.dao.MedicinesDao;
import com.khyr.entity.Charge;
import com.khyr.entity.ChargeItem;
import com.khyr.entity.Medicines;
import com.khyr.service.DrugStatisticsService;
import com.khyr.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author ：Zhang
 * @date ：Created in 2025/3/11 18:41
 * @description：药品销售统计
 * @modified By：
 * @version: 1.0
 */
@Service
public class DrugStatisticsServiceimpl implements DrugStatisticsService {
    @Autowired
    private DrugStatisticsDao drugStatisticsDao;
    @Autowired
    private ChargeDao chargeDao;
    @Autowired
    private MedicinesDao medicinesDao;
    /**
     * @create by: Zr
     * @description: 药品销售列表，根据名称和日期查找，默认为当天
     * @create time: 2025/3/12 14:43
     * @param data
     * @return com.khyr.vo.R<java.util.List<com.khyr.Vo.DrugSalesListVo>>
     */
    @Override
    public R<List<DrugSalesListVo>> select(NameAndDateVo data) {
        // 时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 获取前端传入的名称
        String itemName = data.getItemName();
        // 获取前端传入的时间
        String[] time = data.getDateRange();
        // 创建查询条件
        QueryWrapper<ChargeItem> queryWrapper = new QueryWrapper<>();
        if(itemName != null){
            // 模糊查询
            queryWrapper.like("item_name",itemName);
        }
        // 查询出所有的药品
        queryWrapper.eq("item_type","0");
        // 状态为已支付
        queryWrapper.eq("status","1");
        List<ChargeItem> list = drugStatisticsDao.selectList(queryWrapper);
        List<DrugSalesListVo> drugSalesListVos = new ArrayList<>();
        if(list != null){
            Charge charge =null;
            for(ChargeItem chargeItem:list){
                QueryWrapper<Medicines> queryWrapper1 = new QueryWrapper<>();
                QueryWrapper<Charge> queryWrapper2 = new QueryWrapper<>();
                // 根据订单id查询出订单信息，获取药品出售的时间
                if(time != null){
                    // 根据传入的时间查询
                    queryWrapper2.between("create_time",time[0],time[1]);
                    queryWrapper2.eq("order_id",chargeItem.getOrderId());
                    charge = chargeDao.selectOne(queryWrapper2);
                }else{
                    queryWrapper2.between("create_time", LocalDate.now(), LocalDate.now());
                    queryWrapper2.eq("order_id",chargeItem.getOrderId());
                    charge = chargeDao.selectOne(queryWrapper2);
                }

                // 根据药品名称查询出药品信息，获取药品id
                queryWrapper1.eq("medicines_name",chargeItem.getItemName());
                Medicines medicines = medicinesDao.selectOne(queryWrapper1);
                if(charge != null && medicines != null){
                    // 封装数据
                    DrugSalesListVo drugSalesListVo = new DrugSalesListVo(
                            String.valueOf(medicines.getMedicinesId()),chargeItem.getItemName(),
                            chargeItem.getItemPrice(),chargeItem.getItemNum(), BigDecimal.valueOf(chargeItem.getItemAmount()),
                            sdf.format(charge.getCreateTime()));
                            drugSalesListVos.add(drugSalesListVo);
                }
            }
        }
        return new R<>(200,"查询成功",drugSalesListVos);
    }
    /**
     * @create by: Zr
     * @description: 药品销售统计列表，根据名称和日期查找，默认为当天
     * @create time: 2025/3/12 14:44
     * @param data
     * @return com.khyr.vo.R<java.util.List<com.khyr.Vo.StatisticalListOfDrugSalesVo>>
     */
    @Override
    public R<List<StatisticalListOfDrugSalesVo>> selectDrug(NameAndDateVo data) {
        // 时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 获取前端传入的名称
        String itemName = data.getItemName();
        // 获取前端传入的时间
        String[] time = data.getDateRange();
        // 创建查询条件
        QueryWrapper<ChargeItem> queryWrapper = new QueryWrapper<>();
        if(itemName != null){
            // 模糊查询
            queryWrapper.like("item_name",itemName);
        }
        // 查询出所有的药品
        queryWrapper.eq("item_type","0");
        // 状态为已支付
        queryWrapper.eq("status","1");
        List<ChargeItem> list = drugStatisticsDao.selectList(queryWrapper);
        Map<String, Long> salesCountByItemName = list.stream()
                .collect(Collectors.groupingBy(ChargeItem::getItemName, Collectors.counting()));

        Map<String, Integer> salesQuantityByItemName = list.stream()
                .collect(Collectors.groupingBy(ChargeItem::getItemName,
                        Collectors.summingInt(ChargeItem::getItemNum)));
        //将名称相同的药品金额相加
        Map<String, BigDecimal> salesAmountByItemName = list.stream()
                .collect(Collectors.groupingBy(ChargeItem::getItemName,
                        Collectors.reducing(BigDecimal.ZERO, ChargeItem::getItemPrice, BigDecimal::add)));
        List<StatisticalListOfDrugSalesVo> statisticalListOfDrugSalesVos = new ArrayList<>();
        if(list != null){
            Charge charge =null;
            for(ChargeItem chargeItem:list){
                QueryWrapper<Medicines> queryWrapper1 = new QueryWrapper<>();
                QueryWrapper<Charge> queryWrapper2 = new QueryWrapper<>();
                // 根据订单id查询出订单信息，获取药品出售的时间
                if(time != null){
                    // 根据传入的时间查询
                    queryWrapper2.between("create_time",time[0],time[1]);
                    queryWrapper2.eq("order_id",chargeItem.getOrderId());
                    charge = chargeDao.selectOne(queryWrapper2);
                }else{
                    queryWrapper2.between("create_time", LocalDate.now(), LocalDate.now());
                    queryWrapper2.eq("order_id",chargeItem.getOrderId());
                    charge = chargeDao.selectOne(queryWrapper2);
                }

                // 根据药品名称查询出药品信息，获取药品id
                queryWrapper1.eq("medicines_name",chargeItem.getItemName());
                Medicines medicines = medicinesDao.selectOne(queryWrapper1);
                System.out.println(medicines+"========================="+charge);
                if (charge != null && medicines != null) {
                    // 检查药品是否已经存在于列表中
                    boolean exists = statisticalListOfDrugSalesVos.stream()
                            .anyMatch(vo -> vo.getItemRefId().equals(medicines.getMedicinesId()));

                    // 如果不存在，则封装数据
                    if (!exists) {
                        StatisticalListOfDrugSalesVo statisticalListOfDrugSalesVo =
                                new StatisticalListOfDrugSalesVo(
                                        medicines.getMedicinesId(),
                                        medicines.getMedicinesName(),
                                        salesCountByItemName.get(chargeItem.getItemName()).intValue(),
                                        salesQuantityByItemName.get(chargeItem.getItemName()),
                                        salesAmountByItemName.get(chargeItem.getItemName())
                                );
                        statisticalListOfDrugSalesVos.add(statisticalListOfDrugSalesVo);
                    }
                }

            }
        }
        return new R<>(200,"查询成功",statisticalListOfDrugSalesVos);
    }
    /**
     * @create by: Zr
     * @description: 根据处方id查询该处方下的药品及检查项
     * @create time: 2025/3/12 19:56
     * @param coId
     * @return com.khyr.vo.R<java.util.List<com.khyr.entity.ChargeItem>>
     */
    @Override
    public R<List<ChargeItem>> selectAllByCoId(String coId) {
        QueryWrapper<ChargeItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("co_id",coId);
        List<ChargeItem> chargeItems = drugStatisticsDao.selectList(queryWrapper);
        if(chargeItems != null){
            return new R<>(200,"查询成功",chargeItems);
        }else {
            return new R<>(400,"查询失败",null);
        }
        
    }
}
